﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using JUtil;
using JUtil.Extensions;
using JUtil.WinForm.Extensions;

namespace jCompoment
{
    /// <remarks>
    /// 請以Panel包覆此UserControl
    /// </remarks>>
    public partial class TableSelector : UserControl
    {
        private DbConnectionConfig _dbConnectionConfig;
        private List<string> _tables; 

        public TableSelector()
        {
            this.Load += new EventHandler(TableSelector_Load);

            InitializeComponent();

            _dbConnectionConfig = new DbConnectionConfig
            {
                DbProvider = default(DbProvider),
                ConnectionString = string.Empty
            };
        }

        void TableSelector_Load(object sender, EventArgs e)
        {
            // 版面配置必須在Load，放在constructor作，得不到預期效果
            Dock = DockStyle.Fill;
            clbTables.Height = Height - btnSetup.Height - tbKeyword.Height;
        }

        public void Initialize(DbConnectionConfig dbConnectionConfig, string[] selectedTables)
        {
            _dbConnectionConfig = dbConnectionConfig;

            SetupTables();

            InitTables(selectedTables);
        }

        public DbConnectionConfig GetDbConnectionConfig()
        {
            return _dbConnectionConfig;
        }

        public string[] GetSelectedTables()
        {
            List<string> result = new List<string>();

            for(int i=0; i<clbTables.Items.Count; i++)
            {
                if(clbTables.GetItemChecked(i))
                    result.Add(clbTables.GetItemText(clbTables.Items[i]));
            }
            return result.ToArray();
        }

        private void btnSetup_Click(object sender, System.EventArgs e)
        {
            ConnectionStringEditor editor = string.IsNullOrEmpty(_dbConnectionConfig.ConnectionString)
                ? new ConnectionStringEditor()
                : new ConnectionStringEditor(_dbConnectionConfig.DbProvider, _dbConnectionConfig.ConnectionString);

            DialogResult result = editor.ShowDialog();

            if (DialogResult.OK == result)
            {
                _dbConnectionConfig.DbProvider = editor.GetDbProvider();
                _dbConnectionConfig.ConnectionString = editor.GetConnectionString();

                SetupTables();
                UpdateTables();
            }
        }

        private void SetupTables()
        {
            try
            {
                DbUtil dbUtil = new DbUtil(_dbConnectionConfig);

                _tables = dbUtil.GetTables();
            }
            catch (Exception ex)
            {
                _tables = null;

                Log.E(ex);
            }
        }

        private void InitTables(string[] selectedTables)
        {
            clbTables.Items.Clear();

            List<string> tables = _tables;

            if (tables != null)
            {
                foreach (string table in tables)
                {
                    CheckState initCheckState = CheckState.Unchecked;

                    if (selectedTables != null)
                    {
                        foreach (string selectedTable in selectedTables)
                        {
                            if (table.Equals(selectedTable, StringComparison.OrdinalIgnoreCase))
                            {
                                initCheckState = CheckState.Checked;
                                break;
                            }
                        }    
                    }

                    clbTables.Items.Add(table, initCheckState);
                }
            }
        }

        private void UpdateTables()
        {
            List<string> result = new List<string>();

            if (_tables != null)
            {
                string keyword = tbKeyword.Text;

                if(string.IsNullOrEmpty(keyword))
                    result.AddRange(_tables);
                else
                {
                    string[] tokens = tbKeyword.Text.SplitString(" ");

                    foreach (string table in _tables)
                    {
                        foreach (string token in tokens)
                        {
                            if (table.StartsWith(token, StringComparison.OrdinalIgnoreCase))
                            {
                                result.Add(table);
                                break;
                            }
                        }
                    }
                }
            }

            clbTables.Fill(result.ToArray(), CheckState.Unchecked);
        }

        private void tbKeyword_TextChanged(object sender, EventArgs e)
        {
            UpdateTables();
        }

        
    }
}
